
public class Test43 {
    private static int count = 1;
    private static final Object lock = new Object();
    private static boolean isOddTurn = true; // 奇数线程是否执行

    public static void main(String[] args) {
        // 奇数线程
        new Thread(() -> {
            while (count <= 100) { // 假设打印到100
                synchronized (lock) {
                    if (isOddTurn && count % 2 != 0) {
                        System.out.print(count + " ");
                        count++;
                        isOddTurn = false; // 切换为偶数线程
                        lock.notifyAll(); // 唤醒等待线程
                    } else {
                        try {
                            lock.wait(); // 否则等待
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();

        // 偶数线程
        new Thread(() -> {
            while (count <= 100) {
                synchronized (lock) {
                    if (!isOddTurn && count % 2 == 0) {
                        System.out.print(count + " ");
                        count++;
                        isOddTurn = true; // 切换为奇数线程
                        lock.notifyAll(); // 唤醒等待线程
                    } else {
                        try {
                            lock.wait(); // 否则等待
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
    }
}